package com.lc.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.lc.admin.bean.Device;
import com.lc.admin.bean.DeviceData;
import com.lc.admin.bean.Elder;
import com.lc.admin.dto.HuaweiAuthDto;
import com.lc.admin.mapper.DeviceMapper;
import com.lc.admin.mqtt.RawMessage;
import com.lc.admin.service.IotService;
import com.lc.admin.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
//import com.lc.admin.bean.DeviceData;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class IotServiceImpl implements IotService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DeviceMapper deviceMapper;

    @Override
    public void save(Device device) {
        String token = redisTemplate.opsForValue().get("huawei:auth:token");

        if (StringUtils.isEmpty(token)) {
            // 1、认证
            token = huaweiAuth();
        }
        // 2、请求接口
        StringBuffer productUrl = new StringBuffer("https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/devices");

        // 1、保存数据到华为云
        // 需求：post请求，需要传递json，需要添加请求头，关系响应体
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("X-Auth-Token", token);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        // 生成一个node_id，唯一即可
        device.setNode_id(UUID.randomUUID().toString());
        HttpEntity httpEntity = new HttpEntity(device,httpHeaders);

        ResponseEntity<String> response = restTemplate.exchange(productUrl.toString(), HttpMethod.POST, httpEntity, String.class);
        String body = response.getBody();
        System.out.println("保存到华为云成功");
        System.out.println(body);
        /**
         * {
         * 	"app_id": "754501a66ccd404994597fb101239868",
         * 	"app_name": "DefaultApp_68804yb5",
         * 	"device_id": "68807d2fd582f200183e3bcf_a9d18432-8cb1-4837-bc0c-eee038e89f87",
         * 	"node_id": "a9d18432-8cb1-4837-bc0c-eee038e89f87",
         * 	"gateway_id": "68807d2fd582f200183e3bcf_a9d18432-8cb1-4837-bc0c-eee038e89f87",
         * 	"device_name": "tv03",
         * 	"node_type": "GATEWAY",
         * 	"description": null,
         * 	"fw_version": null,
         * 	"sw_version": null,
         * 	"device_sdk_version": null,
         * 	"auth_info": {
         * 		"auth_type": "SECRET",
         * 		"secret": "458138e845cbbaad25545a075a14609a",
         * 		"secondary_secret": null,
         * 		"fingerprint": null,
         * 		"secondary_fingerprint": null,
         * 		"secure_access": false,
         * 		"timeout": 0
         *        },
         * 	"product_id": "68807d2fd582f200183e3bcf",
         * 	"product_name": "手表",
         * 	"status": "INACTIVE",
         * 	"create_time": "20250724T093823Z",
         * 	"connection_status_update_time": null,
         * 	"active_time": null,
         * 	"tags": [],
         * 	"extension_info": null
         * }
         */
        JSONObject result = JSONObject.parseObject(body);
        String deviceId = result.get("device_id").toString();
        String product_name = result.get("product_name").toString();

        // 2、保存数据到本地数据库
        device.setDevice_id(deviceId);
        device.setProductName(product_name);
//        device.setBindingType();
//        device.setBindingLocation();
//        device.setNoteName();
        deviceMapper.insert(device);
    }

    private String huaweiAuth() {
        // 需求：发送一个post请求，需要传递json数据，还需要添加请求头；关系返回的响应体.
        HuaweiAuthDto params = new HuaweiAuthDto();
        ResponseEntity<String> response = restTemplate.postForEntity("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens", params, String.class);
        List<String> strings = response.getHeaders().get("X-Subject-Token");
        String token = strings.get(0);

        // 存储token到redis中
        redisTemplate.opsForValue().set("huawei:auth:token", token, 23, TimeUnit.HOURS);
        return token;
    }

    @Override
    public Object findDeviceDetail(String deviceId) {
        // 查询设备详情
        // 1、鉴权
        String token = redisTemplate.opsForValue().get("huawei:auth:token");

        if (StringUtils.isEmpty(token)) {
            // 1、认证
            token = huaweiAuth();
        }
        // 2、请求接口
        StringBuffer deviceUrl = new StringBuffer("https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/devices/"+deviceId);

        // 2、调用华为云接口即可
        // 需求：get请求，需要传递header，关心响应体数据
        HttpHeaders header = new HttpHeaders();
        header.set("X-Auth-Token",token);
        HttpEntity entity = new HttpEntity(header);
        ResponseEntity<String> response = restTemplate.exchange(deviceUrl.toString(), HttpMethod.GET, entity, String.class);
        String body = response.getBody();
        System.out.println(JSONObject.parseObject(body));

        // 格式化，封装成VO对象
        return JSONObject.parseObject(body);
    }

    // 查询产品详情，物模型数据
    @Override
    public Object findProduct(String productId) {
        // 查询设备详情
        // 1、鉴权
        String token = redisTemplate.opsForValue().get("huawei:auth:token");

        if (StringUtils.isEmpty(token)) {
            // 1、认证
            token = huaweiAuth();
        }
        // 2、请求接口
        StringBuffer deviceUrl = new StringBuffer("https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/products/"+productId);
        HttpHeaders header = new HttpHeaders();
        header.set("X-Auth-Token",token);
        HttpEntity entity = new HttpEntity(header);
        ResponseEntity<String> response = restTemplate.exchange(deviceUrl.toString(), HttpMethod.GET, entity, String.class);
        String body = response.getBody();

        return JSONObject.parseObject(body);
    }

    @Override
    public void update(Device device) {
        // 查询设备详情
        // 1、鉴权
        String token = redisTemplate.opsForValue().get("huawei:auth:token");

        if (StringUtils.isEmpty(token)) {
            // 1、认证
            token = huaweiAuth();
        }
        // 2、修改华为云的数据
//        StringBuffer deviceUrl = new StringBuffer("https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/devices/"+device.getDevice_id());
//
//        // put请求，提交json，修改请求头，不关心返回结果，判断状态码==200即可
//        HttpHeaders header = new HttpHeaders();
//        header.set("X-Auth-Token",token);
//        header.setContentType(MediaType.APPLICATION_JSON);
//        HttpEntity entity = new HttpEntity(header);
//        restTemplate.exchange(deviceUrl.toString(), HttpMethod.PUT, entity, String.class);

        // 3、修改本地数据库
        deviceMapper.update(device);
    }

    @Override
    public void delDevice(String deviceId) {
        // DELETE /v5/iot/{project_id}/devices/{device_id}
        // 1、删除华为云数据
        // 1、鉴权
        String token = redisTemplate.opsForValue().get("huawei:auth:token");

        if (StringUtils.isEmpty(token)) {
            // 1、认证
            token = huaweiAuth();
        }
        // 2、修改华为云的数据
        StringBuffer deviceUrl = new StringBuffer("https://9830e5aead.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/6dfbfac7de964fc4af3504eab3325722/devices/"+deviceId);
        // 需求：delete请求，设置头，没有json参数，不关心
        HttpHeaders header = new HttpHeaders();
        header.set("X-Auth-Token",token);
        HttpEntity entity = new HttpEntity(header);
        restTemplate.exchange(deviceUrl.toString(), HttpMethod.DELETE, entity, String.class);

        // 2、删除数据库数据
        deviceMapper.del(deviceId);

    }

    /**
     * 接收mqtt订阅的消息
     * @param message
     */
    public void processMessage(RawMessage message) {
        System.out.println("接收到消息-----------------------------------------------------------");
        System.out.println(message.getTopic());
        System.out.println(new String(message.getPayload()));
        String payloadJson = new String(message.getPayload());
        JSONObject payloadObj = JSONObject.parseObject(payloadJson);
        // 1、解析payload
        JSONObject notifyData = payloadObj.getJSONObject("notify_data");
        JSONObject header = notifyData.getJSONObject("header");
        String deviceId = header.getString("device_id");

        // 2、查询设备详情

        Device device = deviceMapper.findById(deviceId);

        // 3、解析properties的值集合，循环写入到数据库
        JSONObject body = notifyData.getJSONObject("body");
        JSONArray services = body.getJSONArray("services");
        for (Object service : services) {
            JSONObject item = (JSONObject) service;
            JSONObject properties = item.getJSONObject("properties");
            for(int i=0;i<properties.size();i++) {
                for (String key : properties.keySet()) {
                    String value = properties.getString(key);

                    //保存数据
                    DeviceData deviceData = new DeviceData();
                    deviceData.setDeviceName(device.getDevice_name());
                    deviceData.setIotId(deviceId);
                    deviceData.setNoteName(device.getNoteName());
                    deviceData.setProductId(device.getProduct_id());
                    deviceData.setProductName(device.getProductName());
                    deviceData.setFunctionName(key);
                    deviceData.setDataValue(value);
                    deviceData.setAccessLocation(device.getRemark());

                    deviceMapper.saveDeviceData(deviceData);
                }
            }
        }
    }
}